package chatClient.view;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
import java.net.*;

//import user created packages
import chatClient.controller.*;
import chat.model.*;
/**  'ChatClientGUI.java'  created by: Team N3 for Swinburne Uni HET715s2/Dr. Recep Ulusoy, 2/10/2012 v0.0 (final)
*	<br>
*   A simple GUI Class program that accompanies the Chat Client program, called by Main.  Its main function is to create 
*   the GUI environment, along with other usual GUI interface management facilities (Help, ClearScreen, etc.).
*	<br>
* 	The purpose of this class is to provide the methods for creating a user interface for 
* 	our chat client.  The constructor is empty, but the class provides the following methods:
* 	@author Tung Nguyen, Trung V Hoang, Rob Bernard, Justin Semmel
* 	@since September 2012
 */

public class ChatClientGUI extends JFrame implements ActionListener, ObserverChatListener, ObservableChatSender{

    private JTextArea messageArea = new JTextArea(15,30); // for the email message body
    private JTextArea responseArea = new JTextArea(15,30); // for the server response etc.
    private JButton sendButton = new JButton("Send");  //use to send the message
    private JButton clearButton = new JButton("Clear Screen");
    private JButton connectButton = new JButton("Connect");
    private JButton disconnectButton = new JButton("Disconnect");
    private JButton helpButton = new JButton("Help");
    private ArrayList <ObserverChatSender> observerList;
    private ChatClientConnection connection;
    private String localHostIpAddress;
    //private static final long serialVersionUID = 1;
    
	//constructor
	public ChatClientGUI(){	
	}
	
	/** 
	*	Initiallise the GUI method
	*/
	public void init()
	{
		//init the observerList
		observerList = new ArrayList<ObserverChatSender>();
		// Init the GUI display
		initUI();		
	}
	/**
	* Clear all text boxes
	*/
	public void clearAll()
	{
		messageArea.setText("");
		responseArea.setText("");		
	}
	/**
	*   Build GUI Window ('initUI' method)
	*   (GUI Display environment setup and implementation, including Buttons and action triggers)
	*/		
    public void initUI()
    {
         
    	setSize(600,650); //Window size and Header
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        InetAddress localHost = null; //Setup Localhost address string
    	try
    	{
        	localHost = InetAddress.getLocalHost(); 
        	localHostIpAddress = localHost.getHostAddress(); 	// Attempt fetch of Localhost address
    	}
    	catch(Exception ex)
    	{
    		ex.printStackTrace();
			//  Diag printout of status
        	System.out.println("LocalHost problem in ChatClientGUI");
    	}
    	
        this.setTitle("HET715 - Group N3 Chat Client v1.0 - " + localHostIpAddress);
              
        Container container = this.getContentPane();		//Invoke display container format
        container.setLayout(new GridBagLayout());      
        GridBagConstraints c = new GridBagConstraints();
        
        Label LResponseArea = new Label("Response Area");	//Label for Response Area
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;				// Label's column
        c.gridy = 0;				// Label's  row
        c.gridwidth = 3;				// No. of columns in component display area
        c.anchor = GridBagConstraints.PAGE_START;
        container.add(LResponseArea,c);    
        
        c.fill = GridBagConstraints.HORIZONTAL;		// Response Area, with Auto-scroll
        c.gridx = 0;					//              (sub-comments as for 2.5 for the rest)
        c.gridy = 1;
        c.gridwidth = 3;
        c.gridheight = 4;
        responseArea.setForeground(Color.blue);
        responseArea.setEditable(false);
        container.add( new JScrollPane(responseArea),c);  	// (area added, with Auto-Scroll)      
        
        c.fill = GridBagConstraints.HORIZONTAL;		// Add 'Clear Screen' button, help
        c.gridx = 4;					//               message and  attach action
        c.gridy = 2;  
        c.insets = new Insets(70,0,0,0);  //top padding
        container.add(clearButton,c);
        clearButton.setToolTipText("Click this button to clear the text boxes");
        clearButton.addActionListener(this);     
        
        c.fill = GridBagConstraints.HORIZONTAL;		// Add 'Connect' button, help message,
        c.insets = new Insets(100,0,0,0);  			//  top-pad position and  attach action
        c.gridx = 4;
        c.gridy = 4;      
        container.add(connectButton,c);
        connectButton.setToolTipText("Click this button to connect to the Chat Server");
        connectButton.addActionListener(this);     	// (action)
        
        c.fill = GridBagConstraints.HORIZONTAL;		// Add 'Disconnect' button, help message,
        c.insets = new Insets(130,0,0,0);  			//               top-pad position and attach action
        c.gridx = 4;
        c.gridy = 4;      
        container.add(disconnectButton,c);
        disconnectButton.setToolTipText("Click this button to disconnect from the Chat Server.");
        disconnectButton.addActionListener(this);    	// (action)
       
        
        Label LmessageArea = new Label("Message Area");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(20,0,0,0);  //top padding
        c.gridx = 1;
        c.gridy = 6;
        c.gridwidth = 3;
        c.anchor = GridBagConstraints.CENTER;
        container.add(LmessageArea,c);
        
        c.fill = GridBagConstraints.HORIZONTAL;		// Message Area, with padding and auto-scroll
        c.insets = new Insets(40,0,0,0);  		// (top padding)
        c.weightx = 2; 
        c.gridx = 0;
        c.gridy = 7;
        c.gridwidth = 3;
        c.gridheight = 4;
        container.add( new JScrollPane(messageArea),c); 	// (area added, with Auto-Scroll)
        
        c.fill = GridBagConstraints.HORIZONTAL;		// Add 'Send text' button, help message 
        c.weightx = 0.5;  					//                 and attach action
        c.gridx = 4;
        c.gridy = 7;       
        container.add(sendButton,c);
        sendButton.setToolTipText("Click this button to send the Message Area text.");
        sendButton.addActionListener(this);    		// (action) 
        
        c.fill = GridBagConstraints.HORIZONTAL;		// Add 'Help' button and attach action
        c.insets = new Insets(100,0,0,0);  //top padding
        c.weightx = 0.5;
        c.gridx = 4;
        c.gridy = 9;       
        container.add(helpButton,c);
        helpButton.addActionListener(this);    		// (action) 
    	
        this.setVisible(true);				//Make display window all visible
    }
    
    public void setConnection(ChatClientConnection theConnection)
    {
    	connection = theConnection;
    }
    
/**
*   ***  3.   Button Manager ('actionPerformed' method)  ***
*                (Activated by a button press ['ActionListener'].
*                 Serially assesses some possible buttons pressed, and implements the desired action for that button)
*
*                 Button test sequence:  first Send button, then Clear Screen, Disconnect, Help
*/
    public void actionPerformed(ActionEvent e)
    {
		//Diagnostic display of button status on CLI screen
    	System.out.println("button clicked");	

		//'Send Text' button check
    	if (e.getSource() == sendButton )	
    	{
			//  Diag printout of status 
        	System.out.println("send button pressed"); 
			//  Send Message area text to Server 
    		String message = messageArea.getText(); 
    		notifyObserverChatSender_SendingMessage(message);
    	}
        else if (e.getSource() == clearButton)
        {
			// 'Clear Screen' button check
			System.out.println("Clear Screen button pressed");
        	clearAll(); //  Clear all text in both boxes
        }
        else if (e.getSource() == connectButton)
        {
			// 'Connect' button check
        	connection.connectToServer();
        }
        
        else if (e.getSource() == disconnectButton)
        {		
		// 'Disconnect' button check
        	connection.disconnectingServer();
        }

    	else if (e.getSource() == helpButton) //'Help' button check
    	{
        	   		
    		JFrame help = new displayHelp();	//  Display Help message for User
                help.setVisible(true);
    	}
    }
 
    
	 /**
	*   Server Response Manager ('updateResponse' method')
	*                (Called by the receiving thread, to update the Respone Area).
	*/
	public void updateResponse(String message)
	{
		System.out.println("Textarea receives a message: " + message);
		responseArea.append("\n" + message);
	}

	public void addObserverChatSender(ObserverChatSender observer)
	{
		observerList.add(observer);
	}
		
	/*
	*   Notify observers of Chat activity ('notifyObserverChat_SendingMessage')
	*	(doesn't need to tell observers when it receives message)
	*/
	public void notifyObserverChatSender_SendingMessage(String message)
	{
		for (ObserverChatSender observer:observerList)
		{
			observer.sendMessage(localHostIpAddress + ": " + message);
		}
	}
}